home *** CD-ROM | disk | FTP | other *** search
/ Collection of Tools & Utilities / Collection of Tools and Utilities.iso / tex / cawf404.zip / getopt.c < prev    next >
C/C++ Source or Header  |  1993-12-07  |  2KB  |  83 lines

  1. /*
  2. Newsgroups: mod.std.unix
  3. Subject: public domain AT&T getopt source
  4. Date: 3 Nov 85 19:34:15 GMT
  5.  
  6. Here's something you've all been waiting for:  the AT&T public domain
  7. source for getopt(3).  It is the code which was given out at the 1985
  8. UNIFORUM conference in Dallas.  I obtained it by electronic mail
  9. directly from AT&T.  The people there assure me that it is indeed
  10. in the public domain.
  11. */
  12.  
  13.  
  14. /*LINTLIBRARY*/
  15.  
  16. #if    !defined(_NEXT_SOURCE)
  17.     extern int strlen();
  18. #endif
  19.  
  20. #define NULL    0
  21. #define EOF    (-1)
  22. #define ERR(s, c)    if(opterr){\
  23.     extern int write();\
  24.     char errbuf[2];\
  25.     errbuf[0] = c; errbuf[1] = '\n';\
  26.     (void) write(2, argv[0], (unsigned)strlen(argv[0]));\
  27.     (void) write(2, s, (unsigned)strlen(s));\
  28.     (void) write(2, errbuf, 2);}
  29.  
  30. extern int strcmp();
  31. extern char *strchr();
  32.  
  33. int    opterr = 1;
  34. int    optind = 1;
  35. int    optopt;
  36. char    *optarg;
  37.  
  38. int
  39. getopt(argc, argv, opts)
  40. int    argc;
  41. char    **argv, *opts;
  42. {
  43.     static int sp = 1;
  44.     register int c;
  45.     register char *cp;
  46.  
  47.     if(sp == 1)
  48.         if(optind >= argc ||
  49.            argv[optind][0] != '-' || argv[optind][1] == '\0')
  50.             return(EOF);
  51.         else if(strcmp(argv[optind], "--") == NULL) {
  52.             optind++;
  53.             return(EOF);
  54.         }
  55.     optopt = c = argv[optind][sp];
  56.     if(c == ':' || (cp=strchr(opts, c)) == NULL) {
  57.         ERR(": illegal option -- ", c);
  58.         if(argv[optind][++sp] == '\0') {
  59.             optind++;
  60.             sp = 1;
  61.         }
  62.         return('?');
  63.     }
  64.     if(*++cp == ':') {
  65.         if(argv[optind][sp+1] != '\0')
  66.             optarg = &argv[optind++][sp+1];
  67.         else if(++optind >= argc) {
  68.             ERR(": option requires an argument -- ", c);
  69.             sp = 1;
  70.             return('?');
  71.         } else
  72.             optarg = argv[optind++];
  73.         sp = 1;
  74.     } else {
  75.         if(argv[optind][++sp] == '\0') {
  76.             sp = 1;
  77.             optind++;
  78.         }
  79.         optarg = NULL;
  80.     }
  81.     return(c);
  82. }
  83.